$('.ui.clear-template').click(function () {
    $('#new-template-form').form('reset');
    $('#sortable').empty();
});

const color = ["primary ", "positive ", "red", "orange", "yellow", "olive", "green", "teal", "blue", "violet", "purple", "pink", "brown", "grey", "negative"];
const color_length = color.length;
$('a.item').click(function () {
    $("a.left-item").removeClass("active");
    $(this).addClass("active");
});
$('a.item.show-template').click(function () {
    $('#template-show').removeClass("hide");
    $('#make-template').addClass("hide");
    $('#craft-description').hide();
    $('#template-management').addClass('hide');
    load_preview_template();
});

$('a.item.add-template').click(function () {
    $('#make-template').removeClass("hide");
    $('#template-show').addClass("hide");
    $('#craft-description').hide();
    $('#template-management').addClass('hide');
})

$('a.item.show-description').click(function () {
    $('#make-template').addClass("hide");
    $('#template-show').addClass("hide");
    $('#craft-description').show();
    $('#template-management').addClass('hide');
})


function load_preview_template() {
    $.get({
        url: '/craft/getAllFirstLevelTemplates',
        success: function (result) {
            if (result.status === 200) {
                let target = $('#template-one-menu');
                package_template_menu(result.data, target);
            }
        }
    })
}

//显示三级模板模态框
$('a.left-item.leave-three-template').click(function () {
    show_modal($(".ui.modal.add-leave-three-template"));
    $('#addLeaveThreeTemplate-btn').removeClass('disabled');
});
let thee_prompt_text;
$.fn.form.settings.rules.checkLeaveThreeTemplate = function () {
    let templateName = $('#leaveThreeTemplateName').val();
    if (verify_template_name(templateName)) {
        thee_prompt_text = "名称不合法";
        $('#addLeaveThreeTemplate-btn').removeClass('disabled');
        return false;
    }
    let flag = false;
    $.get({
        url: '/craft/checkLeaveThreeTemplateName',
        async: false,
        data: {
            "templateName": templateName
        },
        success: function (result) {
            switch (result.status) {
                case 200:
                    flag = true;
                    break;
                case 204:
                    thee_prompt_text = result.msg;
            }
        }
    })
    return flag;
}
//验证三级模板
$('#three-template-form').form({
    inline: true,
    on: 'submit',
    keyboardShortcuts: false,
    fields: {
        leaveThreeTemplateName: {
            identifier: 'leaveThreeTemplateName',
            rules: [
                {
                    type: 'empty',
                    prompt: '请填写模板名称'
                },
                {
                    type: 'regExp',
                    value: /^([a-zA-Z0-9.\-_\u4E00-\u9FA5]+)$/,
                    prompt: "模板名称格式错误"
                },
                {
                    type: 'checkLeaveThreeTemplate',
                    prompt: function () {
                        return thee_prompt_text;
                    }
                }
            ]
        },
        fieldName: {
            identifier: 'fieldName',
            rules: [
                {
                    type: 'empty',
                    prompt: '请填写模板字段名称(驼峰命名 例：PCBASerialCode)'
                },
                {
                    type: 'regExp',
                    value: /^([a-zA-Z0-9]+)$/,
                    prompt: "字段名称格式错误"
                }
            ]
        }
    },
    onSuccess: function () {
        $('#addLeaveThreeTemplate-btn').addClass('disabled');
        add_leave_three_template();
    }
})

//添加三级模板
function add_leave_three_template() {
    $.post({
        url: '/craft/addLeaveThreeTemplate',
        data: {
            "templateName": $('#leaveThreeTemplateName').val(),
            "fieldName": $('#fieldName').val()
        },
        success: function (result) {
            switch (result.status) {
                case 200:
                    $(".ui.modal.add-leave-three-template").modal('hide');
                    $('#three-template-form').form('clear');
                    success(result.msg);
            }
        }
    })
}

let pageNum = 1;
let pageSize = 30;
let twoPageSize=20;
//添加二级模板
$('a.item.leave-two-template').click(function () {
    if (flag) {
        flag = false;
        pageNum = 1;

        $('div .field.templateAlias').addClass('hide');

        init_add_template($(this).text());

        $('#addTemplate-btn').attr("data-value", "two");

        $('#preview-two-template').addClass('hide');

        get_leave_two_template(pageNum, pageSize);
    }
});

function get_leave_two_template(num, size) {
    $.get({
        url: '/craft/getAllLeaveThreeTemplate',
        data: {
            "pageNum": num,
            "pageSize": size
        },
        success: function (result) {
            switch (result.status) {
                case 200:
                    flag = true;
                    package_template_button(result.data, "leave-2", "三级模板", "three-idf");
            }
        }
    })
}

//添加一级模板
$('a.item.leave-one-template').click(function () {
    if (flag) {
        flag = false;
        pageNum = 1;
        init_add_template($(this).text());

        $('div .field.templateAlias').removeClass('hide');

        $('#addTemplate-btn').attr("data-value", "one");

        $('#preview-two-template').removeClass('hide');

        get_leave_one_template(pageNum, twoPageSize);
    }
});

function get_leave_one_template(num, size) {
    $.get({
        url: '/craft/getAllLeaveTwoTemplate',
        data: {
            "pageNum": num,
            "pageSize": size
        },
        success: function (result) {
            switch (result.status) {
                case 200:
                    flag = true;
                    package_template_button(result.data, "leave-1", "二级模板", "two-idf");
            }
        }
    })
}

function init_add_template(text) {
    $('#add-template').removeClass('hide');
    //('#add-template div.header').html("<h2>" + text + "</h2>")
    $('#new-template-form').form('reset');
    $('#sortable').empty();
}

//刷新模板
$(document).on('click', ".reload-template", function () {
    console.log($(this).attr('id'));
    if ($(this).attr('id') === "leave-1") {
        get_leave_one_template(pageNum, twoPageSize);
    } else {
        get_leave_two_template(pageNum, pageSize);
    }
});
//上一页
$(document).on("click", ".pre-page-template", function () {
    if ($('#addTemplate-btn').attr("data-value") === "one") {
        get_leave_one_template(pageNum - 1, twoPageSize)
    } else {
        get_leave_two_template(pageNum - 1, pageSize);
    }
});
//下一页
$(document).on("click", ".next-page-template", function () {
    if ($('#addTemplate-btn').attr("data-value") === "one") {
        get_leave_one_template(pageNum + 1, twoPageSize)
    } else {
        get_leave_two_template(pageNum + 1, pageSize);
    }
})

const reload = "<a class='reload-template'><i class='sync alternate icon'></i>刷新</a><p/>";

const left = "<div style='position:absolute;margin-top:450px;'><button class='ui teal button pre-page-template'><i class='chevron left icon'></i>上一页</button><button class='ui green button next-page-template'><i class='chevron right icon'></i>下一页</button></div>";


//封装模板数据
function package_template_button(data, val, text, idf) {
    //获取容器div
    let container_div = $('#child-template');
    container_div.empty();
    container_div.append("<div class='ui fluid image' style='position: absolute;margin-top: -43px;'><div class='ui black ribbon label'><i class='accusoft icon'></i><font style='vertical-align: inherit;'><font style='vertical-align: inherit;'>" + text + "</font></font></div>");

    container_div.append(reload);

    pageNum = data.pageNum;

    $('.reload-template').attr("id", val);
    $.each(data.list, function (index, item) {
        container_div.append("<div class='item'><div class='ui " + color[parseInt(Math.random() * color_length)] + " " + idf + " button draggable cos' data-value='" + item.templateId + "'><span>" + item.templateName + "</span></div></div>")
    });

    container_div.append(left);
    if (!data.hasPreviousPage) {
        $('.pre-page-template').prop("disabled", true);
    }
    if (!data.hasNextPage) {
        $('.next-page-template').prop("disabled", true);
    }
}


$('#template').change(function () {
    let templateId = $(this).val();
    $.get({
        url: '/craft/previewTemplate',
        data: {
            "templateId": templateId
        },
        success: function (result) {
            if (result.status === 200) {
                let data = result.data;
                head_data_encapsulation(data.template, $('#table1'));
                $('#codes').text(data.productCodes);
                let light = $('#template-light');
                if (data.flag) {
                    light.removeClass('red');
                    light.addClass('green');
                } else {
                    light.addClass('red');
                    light.removeClass('green');
                }
                $('#template-status').text(data.status);
            }
        }
    })
})

function head_data_encapsulation(data, target) {
    // let title = $('#title');
    // title.text(data.leaveOneTemplateName);
    // title.attr("colSpan", data.leaveThreeTemplateName.length);
    let tc = target.find('thead').children();

    let title = tc.eq(0);
    title.html("<th colspan='" + data.leaveThreeTemplateName.length + "'>" + data.leaveOneTemplateName + "</th>");

    let sc = tc.eq(1);

    let content = "";

    $.each(data.leaveTwoTemplateName, function (key, values) {
        content += "<td colspan='" + values + "'>" + key + "</td>"
    });
    sc.html(content);

    content = "";
    let st = tc.eq(2);
    $.each(data.leaveThreeTemplateName, function (index, item) {
        content += "<td>" + item + "</td>"
    });
    st.html(content);
}


$('#new-template-form').form({
    inline: true,
    on: 'submit',
    keyboardShortcuts: false,
    fields: {
        templateName: {
            identifier: 'templateName',
            rules: [
                {
                    type: 'empty',
                    prompt: '请填写模板名称'
                },
                {
                    type: 'regExp',
                    value: /^([a-zA-Z0-9\-_().\u4E00-\u9FA5]+)$/,
                    prompt: "模板名称格式错误"
                }
            ]
        }
    },
    onSuccess: function () {
        if (flag) {
            flag = false;
            add_template();
        }
    }
});

const add_two = '/craft/addLeaveTwoTemplate';
const add_one = '/craft/addLeaveOneTemplate';

function add_template() {
    let data_value = $('#addTemplate-btn').attr("data-value");
    let url;
    let data = pack_up_template_data();
    if (data_value === "one") {
        let templateAlias = $('#templateAlias').val();
        let regExp = new RegExp("([a-z]+)(_)([a-z]+)(_)([a-z]+)");
        if (!regExp.test(templateAlias)) {
            // failure("非法别名");
            $('#new-template-form').form('add prompt', "templateAlias", "非法别名");
            flag = true;
            return;
        }
        data.templateAlias = templateAlias;
        url = add_one;
    } else {
        url = add_two;
    }
    $.post({
        url: url,
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(data),
        success: function (result) {
            switch (result.status) {
                case 200:
                    $('#new-template-form').form('reset');
                    $('#sortable').empty();
                    flag = true;
                    success(result.msg);
            }
        }
    })
}

//上传模板数据封装
function pack_up_template_data() {
    let child = $('#sortable').children('div');
    let list = [];
    let template = {};
    let data = {};
    child.each(function (index) {
        template.name = $(this).children('div').eq(0).children('span').eq(0).text();
        template.childId = $(this).children('div').eq(0).attr("data-value");
        template.orderId = parseInt(index + 1);
        list.push(template);
        template = {};
    });
    data.templateName = $('#templateName').val();
    data.body = list;
    return data;
}

let close_icon = "<i class='close icon'></i>";
let target_div = $('#sortable');
$(document).on("click", "#child-template .ui.button.cos", function () {
    target_div.append($(this).parent().clone().append(close_icon));
});
target_div.sortable({
    containment: 'window',
    cursor: 'pointer',
    forcePlaceholderSize: true
});
$(document).on("click", "#sortable i.close.icon", function () {
    $(this).parent().remove();
});

$('.ui.template.reset.button').click(function () {
    $('#template-form').form('reset');
});

$('a.left-item.bind-template').click(function () {
    show_modal($(".ui.modal.template"));
    load_passed_template();
    $('#bind-template-btn').removeClass('disabled');
});

//获取已通过审核的模板
function load_passed_template() {
    $.get({
        url: '/craft/getAllFirstLevelTemplatesPassed',
        success: function (result) {
            if (result.status === 200) {
                let template = $('#productCode-bind-template-menu');
                package_template_menu(result.data, template);
            }
        }
    })
}

$('#rework-work-bind').click(function () {
    show_modal($(".ui.modal.rework-template"));
    load_rework_template_info();
    $('#rework-btn').removeClass('disabled');
});

$('#rework-update-binding').click(function () {
    show_modal($(".ui.modal.re-update-bind-template"));
    let m1 = $('#re-code-menu');
    let m2 = $('#re-template-menu');
    load_all_reworkOrderNumber(m1, m2);
    $('#re-update-bind-btn').removeClass('disabled');
})

function load_all_reworkOrderNumber(m1, m2) {
    $.get({
        url: '/craft/getAllReworkOrderIsBinding',
        success: function (result) {
            if (result.status === 200) {
                package_menu(result.data.reworkOrder, m1);
                package_template_menu(result.data.templates, m2);
            }
        }
    })
}

$('#update-reworkOrderNumber').change(function () {
    let workOrderNumber = $(this).val();
    if (verify_work_order_number(workOrderNumber)) {
        return;
    }
    $.get({
        url: '/craft/getTemplateInfoByRework/' + workOrderNumber,
        success: function (result) {
            if (result.status === 200) {
                $('#re-oldTemplateId').val(result.data.templateId);
                $('#re-oldTemplateName').val(result.data.templateName);
            }
        }
    })
})

//加载返修工单和模板信息
function load_rework_template_info(m1, m2) {
    $.get({
        url: '/craft/GetAllRepairWorkOrdersAndTemplates',
        success: function (result) {
            if (result.status === 200) {
                let rework_order_menu = $('#rework-order-menu');
                let template = $('#template-four-menu');
                package_menu(result.data.reworkOrder, rework_order_menu);
                package_template_menu(result.data.templates, template);
            }
        }
    })
}

$('#template-form').form({
    inline: true,
    on: 'blur',
    keyboardShortcuts: false,
    fields: {
        productCode: {
            identifier: 'productCode',
            rules: [
                {
                    type: 'empty',
                    prompt: '请填写产品编码'
                }
            ]
        },
        templateId: {
            identifier: 'templateId',
            rules: [
                {
                    type: 'empty',
                    prompt: '请选择模板'
                }
            ]
        }
    },
    onSuccess: function () {
        $('#bind-template-btn').addClass('disabled');
        binding_template();
    }
});
$('#rework-template-form').form({
    inline: true,
    on: 'submit',
    keyboardShortcuts: false,
    fields: {
        reworkOrderNumber: {
            identifier: 'reworkOrderNumber',
            rules: [
                {
                    type: 'empty',
                    prompt: '请选择工单'
                }
            ]
        },
        reworkTemplateId: {
            identifier: 'reworkTemplateId',
            rules: [
                {
                    type: 'empty',
                    prompt: '请选择模板'
                }
            ]
        }
    },
    onSuccess: function () {
        $('#rework-btn').addClass('disabled');
        rework_binding_template();
    }
});

function binding_template() {
    let templateId = $('#templateId').val();
    if (!verify_number(templateId)) {
        failure("非法模板")
        $('#rework-btn').removeClass('disabled');
        return;
    }
    console.log("绑定模板");
    $.post({
        url: '/craft/bindingTemplate',
        data: {
            "productCode": $('#productCode').val(),
            "templateId": templateId
        },
        success: function (result) {
            switch (result.status) {
                case 200:
                    $(".ui.modal.template").modal('hide');
                    $('#template-form').form('clear');
                    success(result.msg);
            }
        }
    })
}

function rework_binding_template() {
    let workOrderNumber = $('#reworkOrderNumber').val();
    let templateId = $('#reworkTemplateId').val();
    if (verify_work_order_number(workOrderNumber) || !verify_number(templateId)) {
        failure("非法参数");
        $('#rework-btn').removeClass('disabled');
        return;
    }
    console.log("绑定模板");
    $.post({
        url: '/craft/reworkOrderBindTemplate',
        data: {
            "workOrderNumber": workOrderNumber,
            "templateId": templateId
        },
        success: function (result) {
            switch (result.status) {
                case 200:
                    $(".ui.modal.rework-template").modal('hide');
                    $('#rework-template-form').form('clear');
                    success(result.msg);
            }
        }
    })
}

$('#update-bind').click(function () {
    show_modal($(".ui.modal.update-bind-template"));
    load_productCode_and_template($('#product-code-menu'), $('#template-three-menu'));
    $('#update-bind-btn').removeClass('disabled');
})

$('#contact-binding').click(function () {
    show_modal($('.ui.modal.contact-binding-modal'))
    load_productCode_and_template($('#product-code-menu-so'), $('#contact-template-menu'));
    $('#contact-bind-btn').removeClass('disabled');
})

$('.re-update-bind.reset').click(function () {
    $('#update-reworkOrderNumber').val("");
    $('#re-newTemplateId').val("");
})

//加载产品编码和模板
function load_productCode_and_template(target1, target2) {
    $.get({
        url: '/craft/getAllProductCodesAndTemplates',
        success: function (result) {
            if (result.status === 200) {
                // let product_menu = $('#product-code-menu');
                // let template = $('#template-three-menu');
                package_menu(result.data.productCodes, target1);
                if (target2 !== null) {
                    package_template_menu(result.data.templates, target2);
                }
            }
        }
    })
}


$('.ui.update-bind.button').click(function () {
    $('#update-bind-form').form('clear');
})

$('.ui.contact-bind.button').click(function () {
    $('#contact-binding-form').form('clear');
})

//选择要更新的产品编码
$('#upProductCode').change(function () {
    $.get({
        url: '/craft/getTheCorrespondingTemplateOfTheProductCode',
        data: {
            "productCode": $(this).val()
        },
        success: function (result) {
            if (result.status === 200) {
                $('#oldTemplate-input').removeClass('disabled');
                let target = $('#old-template-menu');
                package_template_menu(result.data, target);
            }
        }
    })
})

$('#upProductCodeSo').change(function () {
    $.get({
        url: '/craft/getTheCorrespondingTemplateOfTheProductCode',
        data: {
            "productCode": $(this).val()
        },
        success: function (result) {
            if (result.status === 200) {
                let target = $('#contact-template-menu');
                package_template_menu(result.data, target);
            }
        }
    })
})


$('#contact-binding-form').form({
    inline: true,
    on: 'submit',
    keyboardShortcuts: false,
    fields: {
        upProductCodeSo: {
            identifier: 'upProductCodeSo',
            rules: [
                {
                    type: "empty",
                    prompt: "请选择产品编码"
                }
            ]
        },
        contactId: {
            identifier: "contactId",
            rules: [
                {
                    type: "empty",
                    prompt: "请选择模板"
                }
            ]
        }
    },
    onSuccess: function () {
        $('#contact-bind-btn').addClass('disabled');
        contact_template_bind();
    }
})

$('#update-bind-form').form({
    inline: true,
    on: 'submit',
    keyboardShortcuts: false,
    fields: {
        upProductCode: {
            identifier: 'upProductCode',
            rules: [
                {
                    type: 'empty',
                    prompt: '请选择产品编码'
                }
            ]
        },
        oldTemplateId: {
            identifier: 'oldTemplateId',
            rules: [
                {
                    type: 'empty',
                    prompt: '请选择要更改的模板'
                }
            ]
        },
        newTemplateId: {
            identifier: 'newTemplateId',
            rules: [
                {
                    type: 'empty',
                    prompt: '请选择新模板'
                }
            ]
        }
    },
    onSuccess: function () {
        $('#update-bind-btn').addClass('disabled');
        update_template_bind();
    }
})


$('#re-update-bind-form').form({
    inline: true,
    on: 'submit',
    keyboardShortcuts: false,
    fields: {
        workOrderNumber: {
            identifier: 'update-reworkOrderNumber',
            rules: [
                {
                    type: 'empty',
                    prompt: '请选择工单'
                }
            ]
        },
        newTemplateId: {
            identifier: 're-newTemplateId',
            rules: [
                {
                    type: 'empty',
                    prompt: '请选择新模板'
                }
            ]
        }
    },
    onSuccess: function () {
        $('#re-update-bind-btn').addClass('disabled');
        re_update_template_bind();
    }
})


function contact_template_bind() {
    let productCode = $('#upProductCodeSo').val();
    let templateId = $('#contactId').val();
    $.get({
        url: '/craft/contactBinding',
        data: {
            "productCode": productCode,
            "templateId": templateId
        },
        success: function (result) {
            if (result.status === 200) {
                $('#contact-binding-form').form('clear');
                $(".ui.modal.contact-binding-modal").modal('hide');
                success(result.msg);
            }
        }
    })
}

function re_update_template_bind() {
    let oldTemplateId = $('#re-oldTemplateId').val();
    let newTemplateId = $('#re-newTemplateId').val();
    let workOrderNumber = $('#update-reworkOrderNumber').val();
    if (oldTemplateId === newTemplateId) {
        failure("新模板不能和旧模板一样");
        $('#re-update-bind-btn').removeClass('disabled');
        return;
    }
    $.get({
        url: '/craft/updateTheRepairWorkOrderTemplate/' + workOrderNumber + "/" + newTemplateId + "/" + oldTemplateId,
        success: function (result) {
            if (result.status === 200) {
                $('#re-update-bind-form').form('clear');
                $(".ui.modal.re-update-bind-template").modal('hide');
                success(result.msg);
            }
        }
    })
}

function update_template_bind() {
    let oldTemplateId = $('#oldTemplateId').val();
    let newTemplateId = $('#newTemplateId').val();
    if (oldTemplateId === newTemplateId) {
        failure("新模板不能和旧模板一样");
        $('#update-bind-btn').removeClass('disabled');
        return;
    }
    $.post({
        url: '/craft/modifyProductAndTemplateBindingInformation',
        data: {
            "productCode": $('#upProductCode').val(),
            "oldTemplateId": oldTemplateId,
            "newTemplateId": newTemplateId
        },
        success: function (result) {
            if (result.status === 200) {
                $('#update-bind-form').form('clear');
                $(".ui.modal.update-bind-template").modal('hide');
                success(result.msg);
            }
        }
    })
}

$('a.item.head-item.template-management').click(function () {
    get_all_template_information(pageNum, pageSize, 1);
    // $.get({
    //     url: '/index/checkTemplateManagement',
    //     success: function (result) {
    //         if (result.status === 200) {
    //             $('#make-template').addClass('hide');
    //             $('#template-show').addClass('hide');
    //             $('#craft-description').hide();
    //             $('#template-management').removeClass('hide');
    //             get_all_template_information(pageNum, pageSize, 1);
    //         }
    //     }
    // })
});
$('#reload').click(function () {
    if (flag) {
        flag = false;
        get_all_template_information(pageNum, pageSize, 1)
    }
})

function get_all_template_information(start, pageSize, value) {
    $.get({
        url: '/craft/getAllFirstLevelTemplateInformation',
        data: {
            "pageNum": start,
            "pageSize": pageSize
        },
        success: function (result) {
            if (result.status === 200) {
                $('#make-template').addClass('hide');
                $('#template-show').addClass('hide');
                $('#craft-description').hide();
                $('#template-management').removeClass('hide');
                let tbody = $('#table2 tbody');
                package_template_info(result.data.list, tbody);
                renderTfoot(pageSize, result.data, 'get_all_template_information', value, start);
            }
        }
    })
}

const op1 = "<a class='view-template'><i class='eye icon'></i>查看</a><a class='approve'><i class='chess pawn icon'></i>批准</a><a class='delete-template'><i class='trash icon'></i>删除</a>";
const op2 = "<a class='view-template'><i class='eye icon'></i>查看</a><a class='delete-template'><i class='trash icon'></i>删除</a><a class='delete-data'><i class='trash alternate outline icon'></i>删除表数据</a><a class='ds-template'><i class='times icon'></i>禁用</a>";
const op3 = "<a class='view-template'><i class='eye icon'></i>查看</a><a class='delete-template'><i class='trash icon'></i>删除</a><a class='delete-data'><i class='trash alternate outline icon'></i>删除表数据</a><a class='re-template'><i class='sync icon'></i>启用</a>";


function package_template_info(data, target) {
    let template_content = "";
    let operating = "";
    $.each(data, function (index, item) {
        switch (item.templateStatus){
            case "已启用":
                operating=op2;
                break;
            case "禁用":
                operating=op3;
                break;
            default:
                operating=op1;
        }
        template_content += "<tr><td class='hide template-id'>" + item.templateId + "</td><td class='template-name'>" + item.templateName + "</td><td class='template-status'>" + item.templateStatus + "</td><td>" + item.createDate + "</td><td>" + item.author + "</td><td>" + item.productionDate + "</td><td class='operation' style='width: 700px;'>" + operating + "</td></tr>";
    });
    target.html(template_content);
}

//批准
$(document).on("click", '.approve', function () {
    $('.layui-layer-btn0').removeClass('end');
    let cur = $(this);
    layer.confirm('确定审核通过?', {
        btn: ['确定', '取消'],
        icon: 3,
        title: '提示',
        shade: [0.6, '#ffffff', true]
    }, function (index) {
        $('.layui-layer-btn0').addClass('end');
        aprove(cur, index);
        layer.close(index);
    });
});

//执行批准
function aprove(target, index) {
    let cur = target.parent();
    let template_id = cur.siblings('.template-id').text();
    let template_name = cur.siblings('.template-name').text();
    if (!verify_number(template_id) || verify_template_name(template_name)) {
        layer.close(index);
        failure("请勿篡改前端数据")
        return;
    }
    $.get({
        url: '/craft/approved',
        data: {
            "templateId": template_id,
            "templateName": template_name
        },
        success: function (result) {
            if (result.status === 200) {
                cur.siblings('.template-status').text(result.data);
                cur.html(op1);
                success(result.msg);
            }
        }
    })
}

$(document).on("click", '.ds-template', function () {
    let cur = $(this).parent();
    Notiflix.Confirm.Show('禁用模板', '是否禁用模板?', '确定', '取消', function () {
        ds_template(cur);
    }, function () {

    });
});

function ds_template(target) {
    let template_id = target.siblings('.template-id').text();
    console.log(target);
    if (!verify_number(template_id)) {
        failure("请勿篡改数据");
        return;
    }
    $.get({
        url: '/craft/disabledTemplate/' + template_id,
        success: function (result) {
            if (result.status === 200) {
                target.siblings('.template-status').text(result.data);
                target.html(op3);
                success(result.msg);
            }
        }
    })
}

$(document).on("click", '.re-template', function () {
    let cur = $(this).parent();
    Notiflix.Confirm.Show('启用模板', '是否启用模板?', '确定', '取消', function () {
        re_template(cur);
    }, function () {

    });
});

function re_template(target) {
    let template_id = target.siblings('.template-id').text();
    if (!verify_number(template_id)) {
        failure("请勿篡改数据");
        return;
    }
    $.get({
        url: '/craft/enabledTemplate/' + template_id,
        success: function (result) {
            if (result.status === 200) {
                target.siblings('.template-status').text(result.data);
                target.html(op2);
                success(result.msg);
            }
        }
    })
}


//查看模板
$(document).on("click", '.view-template', function () {
    let template_id = $(this).parent().siblings('.template-id').text();
    if (!verify_number(template_id)) {
        failure("请勿篡改数据");
        return;
    }
    $.get({
        url: '/craft/previewTemplate',
        data: {
            "templateId": template_id
        },
        success: function (result) {
            if (result.status === 200) {
                show_modal($('.ui.modal.template-modal'));
                head_data_encapsulation(result.data.template, $('#table3'));
            }
        }
    })
});
//删除表数据
$(document).on("click", ".delete-data", function () {
    let cur = $(this);
    $('.layui-layer-btn0').removeClass('end');
    layer.confirm('确定要清空此模板下的所有数据?', {
        btn: ['确定', '取消'],
        icon: 0,
        title: '警告',
        shade: [0.6, '#ffffff', true]
    }, function (index) {
        $('.layui-layer-btn0').addClass('end');
        delete_table_data(cur, index);
        layer.close(index);
    });
})

function delete_table_data(target, index) {
    let template_id = target.parent().siblings('.template-id').text();
    if (!verify_number(template_id)) {
        layer.close(index);
        failure("请勿篡改前端数据")
        return;
    }
    $.get({
        url: '/craft/deleteTableData',
        data: {
            "templateId": template_id
        },
        success: function (result) {
            if (result.status === 200) {
                success(result.msg);
            }
        }
    })
}

$(document).on("click", ".delete-template", function () {
    let cur = $(this);
    $('.layui-layer-btn0').removeClass('end');
    layer.confirm('确定要删除模板?', {
        btn: ['确定', '取消'],
        icon: 3,
        title: '提示',
        shade: [0.6, '#ffffff', true]
    }, function (index) {
        $('.layui-layer-btn0').addClass('end');
        delete_template(cur, index);
        layer.close(index);
    });
});

function delete_template(target, index) {
    let template_id = target.parent().siblings('.template-id').text();
    if (!verify_number(template_id)) {
        layer.close(index);
        failure("请勿篡改前端数据")
        return;
    }
    $.get({
        url: '/craft/deleteTemplate',
        data: {
            "templateId": template_id
        },
        success: function (result) {
            if (result.status === 200) {
                target.parent().parent().remove();
                success(result.msg);
            }
        }
    })
}


$(document).on('click', '.two-idf.button.draggable.cos', function () {
    let idf_text = $('#idf-text');
    let val = idf_text.val();
    let templateId = $(this).attr("data-value");
    idf_text.val(templateId);
    if (!verify_number(templateId) || val === templateId) {
        return;
    }
    $.get({
        url: '/craft/getChildTemplateInformation',
        data: {
            "templateId": templateId
        },
        success: function (result) {
            if (result.status === 200) {
                package_child_template(result.data);
            }
        }
    })
});

function package_child_template(data) {
    let tr = $('#table4 thead').children();
    let title = tr.eq(0);
    let child = tr.eq(1);
    title.html("<th colspan='" + data.parentLength + "'>" + data.parentName + "</th>")

    let text = "";
    $.each(data.childName, function (index, item) {
        text += "<td>" + item + "</td>";
    });
    child.html(text);
}

let level_idf;

const del_url1 = "/craft/deleteLevelTwoTemplate";

const del_url2 = "/craft/deleteLevelThreeTemplate";

$('.del-level-two').click(function () {
    open_del_modal();
    load_unused_two_template();
});

$('.del-level-three').click(function () {
    open_del_modal();
    load_unused_three_template();
});

$('.ui.del-template.reset.button').click(function () {
    $('#del-template-form').form('reset');
});

function open_del_modal() {
    $('.ui.modal.del-template-modal').modal({
        closable: false
    }).modal("show");
    $('#delTemplate-btn').removeClass('disabled');
}

//加载未被使用的三级模板
function load_unused_three_template() {
    level_idf = del_url2;
    $.get({
        url: '/craft/getUnusedThreeLevelTemplates',
        success: function (result) {
            if (result.status === 200) {
                package_template_menu(result.data, $('#del-template-menu'));
            }
        }
    })
}

//加载未被使用的二级模板
function load_unused_two_template() {
    level_idf = del_url1;
    $.get({
        url: '/craft/getUnusedTwoLevelTemplates',
        success: function (result) {
            if (result.status === 200) {
                package_template_menu(result.data, $('#del-template-menu'));
            }
        }
    })
}

$('#del-template-form').form({
    inline: true,
    on: "submit",
    keyboardShortcuts: false,
    fields: {
        templateId: {
            identifier: "del-templateId",
            rules: [
                {
                    type: "empty",
                    prompt: "请选择模板"
                }
            ]
        },
        reason: {
            identifier: "del-reason",
            rules: [
                {
                    type: "empty",
                    prompt: "请填写删除原因"
                }
            ]
        }
    },
    onSuccess: function () {
        let target = $('#delTemplate-btn');
        del_unused_child_template(target);
        target.addClass('disabled');
    }
});

function del_unused_child_template(target) {
    let templateId = $('#del-templateId').val();
    let reason = $('#del-reason').val();
    if (!verify_number(templateId) || reason === "") {
        target.removeClass('disabled');
        failure("参数错误");
        return;
    }
    $.get({
        url: level_idf,
        data: {
            "templateId": templateId,
            "reason": reason
        },
        success: function (result) {
            if (result.status === 200) {
                $('.ui.modal.del-template-modal').modal("hide");
                success(result.msg);
            }
        }
    })
}